﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Net;
using System.IO;
using System.Text;
using System.Web.Script.Serialization;
using weikebuluo.DAL;
using weikebuluo.Common;
using System.Collections.Specialized;
using weikeweixin.web.wechat.api;


namespace weikeweixin.web.wechat.api.cs
{
    public class common
    {
        //创建菜单接口
        public static string setMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={0}";
        //获取微信凭证access_token的接口
        public static string getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
        //上传图文消息的接口
        public static string getuploadnewsUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}";
        //根据分组进行群发
        public static string postMessageUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
        //根据分组进行群发
        public static string postGroupaddUrl = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token={0}";
        public static string postGrouplistUrl = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token={0}";//获取分组
        //浏览器用于 HTTP 请求的用户代理头的值 
        public static string userAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22";

        w_caidan_dal caidandal = new w_caidan_dal();//菜单
        w_wechat_dal wechatdal = new w_wechat_dal();
        JavaScriptSerializer Jss = new JavaScriptSerializer();
       
        public common()
        { }

        #region 菜单Json数据
        public string GetMenuJson(string wechat_id)
        {
            string menuJson = "";

            DataTable dtMenu = caidandal.GetList("wechat_id=" + wechat_id).Tables[0];

            if (dtMenu.Rows.Count > 0)
            {
                int i = 1;
                menuJson = "{\"button\":[";
                DataRow[] menuRows = dtMenu.Select("caidan_layid is Null or caidan_layid='0'", "caidan_order");

                foreach (DataRow Row in menuRows)
                {
                    DataRow[] secondRows = dtMenu.Select("caidan_layid=" + Row["caidan_id"], "caidan_order");

                    if (secondRows.Length > 0)
                    {
                        menuJson += "{";
                        menuJson += "\"name\":\"" + Row["caidan_name"].ToString() + "\",";
                        menuJson += "\"sub_button\":[";

                        #region 子菜单
                        int j = 1;
                        foreach (DataRow secondRow in secondRows)
                        {
                            menuJson += "{";
                            menuJson += "\"type\":\"" + secondRow["caidan_type"].ToString() + "\",";
                            menuJson += "\"name\":\"" + secondRow["caidan_name"].ToString() + "\",";
                            menuJson += "\"key\":\"" + secondRow["caidan_key"].ToString() + "\",";
                            menuJson += "\"url\":\"" + secondRow["caidan_url"].ToString() + "\"";
                            menuJson += "}";

                            if (secondRows.Length != j)
                            {
                                menuJson += ",";
                            }

                            j++;
                        }
                        #endregion 子菜单

                        menuJson += " ]}";
                    }
                    else
                    {
                        menuJson += "{";
                        menuJson += "\"type\":\"" + Row["caidan_type"].ToString() + "\",";
                        menuJson += "\"name\":\"" + Row["caidan_name"].ToString() + "\",";
                        menuJson += "\"key\":\"" + Row["caidan_key"].ToString() + "\",";
                        menuJson += "\"url\":\"" + Row["caidan_url"].ToString() + "\"";
                        menuJson += "}";
                    }

                    if (menuRows.Length != i)
                    {
                        menuJson += ",";
                    }

                    i++;
                }

                menuJson += "]}";
            }

            return menuJson;
        }
        #endregion 菜单Json数据

        #region 发布菜单
        public string SetMenu(string wechat_id)
        {
            string respText = "";
            string menuJson = GetMenuJson(wechat_id);
            string accessToken = GetAccessToken(wechat_id);
            string url = string.Format(setMenuUrl, accessToken);
            byte[] requestBytes = Encoding.UTF8.GetBytes(menuJson);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = requestBytes.Length;

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(requestBytes, 0, requestBytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }

            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);

            return respDic["errcode"].ToString();
        }
        #endregion 发布菜单

        #region 获取微信凭证
        public string GetAccessToken(string wechat_id)
        {
            string accessToken = "";

            DataTable dtwecaht = wechatdal.GetList("wechat_id='" + wechat_id + "'").Tables[0];

            if (dtwecaht.Rows.Count > 0)
            {
                string respText = "";
                string wechat_appid = dtwecaht.Rows[0]["wechat_appid"].ToString();
                string wechat_appsecret = dtwecaht.Rows[0]["wechat_appsecret"].ToString();
                string url = string.Format(getAccessTokenUrl, wechat_appid, wechat_appsecret);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                using (Stream resStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(resStream, Encoding.Default);
                    respText = reader.ReadToEnd();
                    resStream.Close();
                }

                Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);

                accessToken = respDic["access_token"].ToString();
            }

            return accessToken;
        }
        #endregion 获取微信凭证

        #region 发送文本
        public string postexttmessage(string wechat_id, string content,string id)
        {
            string respText = "";
            string menuJson = "{\"filter\":{\"group_id\":\"" + id + "\"},\"text\":{\"content\":\"" + content + "\"}, \"msgtype\":\"text\"}";
            string accessToken = GetAccessToken(wechat_id);
            string url = string.Format(postMessageUrl, accessToken);
            byte[] requestBytes = Encoding.UTF8.GetBytes(menuJson);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = requestBytes.Length;

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(requestBytes, 0, requestBytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//返回来自inertnet的响应

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }

            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);

            return respDic["errcode"].ToString();//发送返回的错误码

        }
        #endregion 发送文本

        #region 新建分组
        public string groupadd(string wechat_id, string name)
        {
            string respText = "";
            string groupJson = "{\"group\":{\"name\":\"" + name + "\"}}";
            string accessToken = GetAccessToken(wechat_id);
            string url = string.Format(postGroupaddUrl, accessToken);
            byte[] requestBytes = Encoding.UTF8.GetBytes(groupJson);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = requestBytes.Length;

            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(requestBytes, 0, requestBytes.Length);
                reqStream.Flush();
                reqStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();//返回来自inertnet的响应

            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.Default);
                respText = reader.ReadToEnd();
                resStream.Close();
            }

            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(respText);
            return respDic["group"].ToString();

        }
        #endregion 新建分组

        #region 分组列表
        public string grouplist(string wechat_id)
        {
            string respText = "";
            string accessToken = GetAccessToken(wechat_id);
            string url = string.Format(postGrouplistUrl, accessToken);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            using (Stream resStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(resStream, Encoding.UTF8);
                respText = reader.ReadToEnd();
                //respText = System.Web.HttpContext.Current.Server.UrlDecode(respText);
                resStream.Close();
            }
            string respDic = Jss.Serialize(respText);
            return respDic;
        }
        #endregion 分组列表

          

        #region  post提交带数据流数据
        //NameValueCollection nvc = new NameValueCollection();
        //nvc.Add("jia-V", "收集");
        public string UploadFileByHttpWebRequest(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream rs = wr.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            if (nvc != null)
            {
                foreach (string key in nvc.Keys)
                {
                    rs.Write(boundarybytes, 0, boundarybytes.Length);
                    string formitem = string.Format(formdataTemplate, key, nvc[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                    rs.Write(formitembytes, 0, formitembytes.Length);
                }
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();

            WebResponse wresp = null;
            var result = "";
            try
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                //成功回傳結果
                result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (wresp != null)
                    wresp.Close();
            }
            wr = null;
            return result;
        }
        #endregion

    }
}